<template>
  <view class="room-container">
    <view class="room-info">
      <text class="room-id">房间ID: {{ room_id }}</text>
      
      <button class="share-btn" @click="openShareModal">
        <text>邀请好友</text>
      </button>
      
      <view class="members-list">
        <text class="section-title">成员列表</text>
        <view class="member-item" v-for="(member, index) in members" :key="index">
          <image :src="member.avatar" class="avatar" />
          <text>{{ member.name }}</text>
        </view>
      </view>
    </view>
    
    <!-- 分享模态窗口 -->
    <view class="modal-mask" v-if="showShareModal" @click="closeModal">
      <view class="modal-container" @click.stop>
        <view class="modal-header">
          <text class="modal-title">邀请好友加入</text>
          <button class="close-btn" @click="closeModal">×</button>
        </view>
        
        <view class="modal-content">
          <text class="room-id-text">房间ID: {{ room_id }}</text>
          <view class="qr-code-container">
            <canvas canvas-id="qrCanvas" class="qr-code" :style="{width: qrSize + 'px', height: qrSize + 'px'}"></canvas>
          </view>
          <text class="tip-text">请使用「扫码加入」扫描二维码</text>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeModal">取消</button>
          <button class="confirm-btn" @click="saveQRCode">保存二维码</button>
        </view>
      </view>
    </view>
	
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import drawQrcode from 'weapp-qrcode'
import { onLoad } from '@dcloudio/uni-app'

// 房间基础信息
const room_id = ref('123asd')
const showShareModal = ref(false) // 控制模态窗口显示/隐藏
const qrSize = ref(200) // 二维码尺寸
const members = ref([ // 成员列表数据
  { id: 1, name: '用户1', avatar: '/static/avatar1.png' },
  { id: 2, name: '用户2', avatar: '/static/avatar2.png' }
])

// 页面加载时初始化二维码尺寸（适配不同屏幕）
onMounted(() => {
  const systemInfo = uni.getSystemInfoSync()
  // 二维码尺寸取屏幕宽度60%和300px的最小值，避免超出屏幕
  qrSize.value = Math.min(systemInfo.windowWidth * 0.6, 300)
})

// 生成二维码（调用weapp-qrcode库）
const generateQRCode = () => {
  drawQrcode({
    canvasId: 'qrCanvas', // 对应canvas的id
    text: room_id.value, // 二维码内容（房间ID）
    width: qrSize.value,
    height: qrSize.value,
    colorDark: '#000000', // 二维码深色
    colorLight: '#ffffff', // 二维码浅色（背景）
    correctLevel: 1 // 纠错等级（1-3，等级越高容错性越强）
  })
}

// 打开分享模态窗口
const openShareModal = () => {
  showShareModal.value = true
  // 延迟生成二维码（确保模态窗口已渲染，避免canvas未加载导致绘制失败）
  setTimeout(() => {
    generateQRCode()
  }, 500)
}

// 关闭模态窗口
const closeModal = () => {
  showShareModal.value = false
}

// 保存二维码到本地相册
const saveQRCode = () => {
  // 将canvas内容转为临时图片路径
  uni.canvasToTempFilePath({
    canvasId: 'qrCanvas',
    success: (res) => {
      // 保存图片到相册
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: () => {
          uni.showToast({ title: '保存成功', icon: 'success' })
        },
        fail: () => {
          uni.showToast({ title: '保存失败', icon: 'none' })
        }
      })
    }
  })
}

// 验证房间并加入（未在模板中调用，可根据需求绑定触发）
const validateAndJoinRoom = async () => {
  try {
    // 从本地存储获取用户信息
    const userData = JSON.parse(uni.getStorageSync('user'))
    const user_id = userData.userinfo.userid

    // 调用后端接口验证房间是否存在
    const { data } = await uni.request({
      url: `http://172.16.24.120:5000/mysqlroom/check_room`,
      method: 'POST',
      data: { room_id: room_id.value, user_id }
    })

    if (data.exists) {
      // 房间存在，通过WebSocket加入
      socket.emit('jinfangjian', { room_id: room_id.value, user_id })
    } else {
      // 房间不存在，提示并返回上一页
      uni.showToast({ title: '房间不存在', icon: 'none' })
      setTimeout(() => uni.navigateBack(), 1000)
    }
  } catch (error) {
    uni.showToast({ title: '网络错误', icon: 'none' })
  }
}
</script>

<style lang="scss">
/* 动画定义：模态窗口打开时的旋转进入效果 */
@keyframes rotateIn {
  from {
    opacity: 0; /* 初始完全透明 */
    transform: rotate(-20deg) scale(0.5); /* 初始状态：向左旋转20度+缩小到0.5倍 */
  }
  to {
    opacity: 1; /* 结束时完全显示 */
    transform: rotate(0deg) scale(1); /* 结束状态：正常角度+正常大小 */
  }
}

.room-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh; /* 占满整个屏幕高度 */
}

.room-info {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05); /* 轻微阴影 */
}

.room-id {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 24rpx;
  display: block; /* 独占一行 */
}

.share-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 240rpx;
  height: 80rpx;
  margin: 20rpx auto 40rpx;
  background-color: #409EFF;
  color: white;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
  
  image {
    width: 36rpx;
    height: 36rpx;
    margin-right: 10rpx;
  }
}

.members-list {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: block;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #eee;
  
  &:last-child {
    border-bottom: none; /* 最后一个成员取消下边框 */
  }
  
  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%; /* 圆形头像 */
    margin-right: 20rpx;
  }
}

/* 模态窗口样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* 确保在最上层 */
}

.modal-container {
  width: 80%;
  max-width: 600rpx;
  background-color: white;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
  /* 应用旋转进入动画 */
  animation: rotateIn 0.4s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  background-color: #f5f5f5;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 44rpx;
  color: #999;
  background: transparent;
  border: none;
  padding: 0;
  line-height: 1;
}

.modal-content {
  padding: 40rpx 32rpx;
  text-align: center;
  
  .room-id-text {
    font-size: 30rpx;
    color: #409EFF; /* 突出显示房间ID */
    margin-bottom: 30rpx;
    display: block;
  }
  
  .tip-text {
    font-size: 26rpx;
    color: #888;
    margin-top: 30rpx;
    display: block;
  }
}

.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30rpx auto;
  padding: 20rpx;
  background-color: #fff;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
}

.qr-code {
  display: block;
}

.modal-footer {
  display: flex;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
  
  button {
    flex: 1; /* 两个按钮平分宽度 */
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 10rpx;
    font-size: 30rpx;
    margin: 0 10rpx;
    border: none;
    
    &.cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }
    
    &.confirm-btn {
      background-color: #409EFF;
      color: white;
    }
  }
}
</style>